import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import filter from "./filter/filter";
import * as echarts from 'echarts';
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

Vue.config.productionTip = false
Vue.prototype.$ajax = axios;
Vue.prototype.$echarts = echarts;
require('echarts/theme/roma');
require('echarts/theme/macarons');
require('echarts/theme/shine');
require('echarts/theme/infographic');
require('echarts/theme/vintage');

// 事件总线EventBus
Vue.prototype.$event = new Vue();
Vue.use(mavonEditor);

Object.keys(filter).forEach(key => {
  Vue.filter(key,filter[key])
});

/**
 * axios拦截器，请求头携带token，后端验证token时效性，若失效，则提示登录，
 */
axios.interceptors.request.use(function (config) {
  let token = Tool.getLoginUser().token;
  if (Tool.isNotEmpty(token)){
    config.headers.token = token;
    console.log("请求headers增加token: ",token);
  }
  return config;
}, error => {});
axios.interceptors.response.use(function (response) {
  return response;
}, error => {
  console.log("返回拦截：",error.response);
  let response = error.response;
  const status = response.status;
  if(status === 401){
    console.log("未登录");
    Tool.setLoginUser(null);
    // 触发打开登录窗口事件，用到事件总线
    Vue.prototype.$event.$emit("openLoginModal");
  }
  if(status === 404) {
    console.log("not found");
    router.push('/error');
  }
  return {
    data: {
      success: false,
      message: "请重新登录"
    }
  }
});


// 路由登录拦截
// 从缓存中取得登录信息，若缓存中有用户信息，则可以跳转
// 若无用户信息，则退到欢迎页面（还可以考虑弹出登录框）
router.beforeEach((to,from,next) => {
  // 要不要对meta.loginRequire属性做监控拦截
  if(to.matched.some(function (item) {
    return item.meta.loginRequire;
  })){
    let loginUser = Tool.getLoginUser();
    if(Tool.isEmpty(loginUser)){
      // 触发打开登录窗口事件，用到事件总线
      Vue.prototype.$event.$emit("openLoginModal");
    }else{
      next();
    }
  }else{
    next();
  }
})


new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
